package dbops

import (
	"video/api/defs"
	"github.com/satori/go.uuid"
	"time"
)

func AddUser(loginUserName string, pwd string) error {
	stmt, e := conn.Prepare("insert into users (login_name, pwd) VALUES (?,?)")
	if e != nil {
		return e
	}
	defer stmt.Close()
	_, e1 := stmt.Exec(loginUserName, pwd)
	return e1
}

func GetUser(loginUserName string) (string, error) {
	stmt, e := conn.Prepare("select pwd from users where login_name = ?")
	if e != nil {
		return "", e
	}
	defer stmt.Close()
	var pwd string
	e1 := stmt.QueryRow(loginUserName).Scan(&pwd)
	if e1 != nil {
		return "", e1
	}
	return pwd, nil
}

func DeleteUser(loginUserName string) error {
	stmt, e := conn.Prepare("delete from users where login_name = ?")
	if e != nil {
		return e
	}
	defer stmt.Close()
	_, e1 := stmt.Exec(loginUserName)
	return e1
}

func AddVideo(aid int, name string) (*defs.Video, error) {
	//uuid
	u1, e := uuid.NewV4()
	if e != nil {
		return nil, e
	}
	uuidString := u1.String()
	t := time.Now()
	ctime := t.Format("Jan 02 2006, 15:04:05")
	stmt, e1 := conn.Prepare("insert into video (id,author_id,name,display_time) values (?,?,?,?)")
	if e1 != nil {
		return nil, e1
	}
	defer stmt.Close()
	_, e2 := stmt.Exec(uuidString, aid, name, ctime)
	if e2 != nil {
		return nil, e2
	}
	return &defs.Video{
		Id:           uuidString,
		Aid:          aid,
		Name:         name,
		DisplayCtime: ctime,
	}, nil
}

func AddComment(aid int, vid string, content string) error {
	//uuid
	u1, e := uuid.NewV4()
	if e != nil {
		return e
	}
	uuidString := u1.String()
	stmt, e1 := conn.Prepare("insert into comments (id,author_id,video_id,content) values (?,?,?,?)")
	if e1 != nil {
		return e1
	}
	defer stmt.Close()
	_, e2 := stmt.Exec(uuidString, aid, vid, content)
	return e2
}

func GetComments(vid string, from, to int) ([]*defs.Comment, error) {
	stmt, e1 := conn.Prepare(`select u.login_name as name,c.content as content,c.id as id 
									from comments c inner join users u on u.id = c.author_id
									where c.video_id = ? and c.time > FROM_UNIXTIME(?) and c.time <= FROM_UNIXTIME(?)`)
	if e1 != nil {
		return nil, e1
	}
	defer stmt.Close()
	rows, e2 := stmt.Query(vid, from, to)
	if e2 != nil {
		return nil, e2
	}
	comments := make([]*defs.Comment, 0)
	for rows.Next() {
		var name, id, content string
		rows.Scan(&name, &content, &id)
		comments = append(comments, &defs.Comment{Id: id, Content: content, Author: name, VideoId: vid})
	}
	return comments, nil
}
